package com.fangshi.util

import android.content.Context
import android.media.AudioManager
import android.media.SoundPool
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.fangshi.R

class SoundPlayer(private val context: Context) : LifecycleEventObserver {
    lateinit var sp: SoundPool
    var soundId: Int? = null

    fun play() {
        val am = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        val audioMaxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC).toFloat()
        val audioCurrentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC).toFloat()
        val volRatio = audioCurrentVolume / audioMaxVolume
        sp.play(soundId!!, volRatio, volRatio, 0, 0, 1f)
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when (event) {
            Lifecycle.Event.ON_CREATE -> {
                sp = SoundPool(4, AudioManager.STREAM_MUSIC, 4)
                soundId = sp.load(context, R.raw.msg, 1)
            }
            Lifecycle.Event.ON_DESTROY -> {
                sp.release()
            }
            else -> {
            }
        }
    }
}